package com.zst.dollars.handler.server;

import com.zst.dollars.common.Consts;
import com.zst.dollars.entity.keepalive.KeepAliveResponseMessage;
import com.zst.dollars.entity.keepalive.KeepAliveRequestMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 处理收到的客户端心跳包回复
 */
public class ClientKeepAliveResponseHandler extends SimpleChannelInboundHandler<KeepAliveResponseMessage> {
    private static final Logger logger = LoggerFactory.getLogger(ClientKeepAliveResponseHandler.class);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, KeepAliveResponseMessage msg) throws Exception {
        logger.debug("收到客户端{}的心跳包", ctx.channel().attr(Consts.tokenKey).get());
        //心跳计数置0
        AtomicInteger keepAliveCount = ctx.channel().attr(Consts.keepAliveCount).get();
        keepAliveCount.set(0);
    }

    /**
     * 添加定时发送心跳包的定时任务
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().eventLoop().scheduleAtFixedRate(() -> {
            KeepAliveRequestMessage keepAliveRequestMessage = new KeepAliveRequestMessage();

        }, 5, 20, TimeUnit.SECONDS);
    }
}
